import router from "@/router";
import axios from "axios";
import { ElMessage } from 'element-plus'
// 初始化 axios 实例
const axiosInstance = axios.create({
    baseURL: "/api",
    // timeout: 1200000 // 请求超时时间，毫秒（默认2分钟
});
// 拦截器
// request拦截器
axiosInstance.interceptors.request.use(requestInfo => {
    if (requestInfo.headers) {
        requestInfo.headers['token'] = localStorage.getItem('token') || "0";
        requestInfo.headers['Content-Type'] = 'application/json;charset=UTF-8';
        return requestInfo
    }
},
    error => {
        return Promise.reject(error)    
    }
)


// response 拦截器
axiosInstance.interceptors.response.use(response => {
    const res = response.data
    if (res.code === 200) {
        return res
    } else if (res.code === 10001) {
        ElMessage.error('登录过期，请登录')
        router.push({ path: '/login' })
    } else if (res.code === 10002) {
        ElMessage({
            message: '权限不足',
            type: 'warning',
        })
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }
})
export default axiosInstance;
